//
//  FYNetworkTools.swift
//  dugeweibo
//
//  Created by pelesys on 16/8/6.
//  Copyright © 2016年 杜方宜. All rights reserved.
//
//tool.lu 程序员工具箱
//failed: unacceptable content-type: text/html  text/plain
//AFN默认只支持以下几种数据格式的解析 @"application/json", @"text/json", @"text/javascript"
import AFNetworking
//定义枚举类型
enum RequestType:String{
    case GET = "GET"
    case POST = "POST"
}
class NetworkTools: AFHTTPSessionManager {
    //let是线程安全的
    //定义单利对象
    static let shareInstance:NetworkTools = {
        let tools = NetworkTools()
//        tools.requestSerializer = [AFHTTPRequestSerializer serializer];
        tools.requestSerializer = AFHTTPRequestSerializer()
        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        
        return tools
        
    }()
    
}
// MARK:-封装请求方法
extension NetworkTools{
    func request(methodType:RequestType,urlString:String,parameters : [String:Any]?,finished : @escaping(_ result :Any?, _ error : Error? )->()){
        //1.定义成功的回调闭包
        let successCallBack:((URLSessionDataTask, Any?) -> Void)? = {(task : URLSessionDataTask?,result :Any?) -> Void in
            finished(result, nil)
        }
        //2.定义失败的回调闭包
        let failureCallBack:((URLSessionDataTask?, Error) -> Void)? = { (task : URLSessionDataTask?,error : Error) -> Void in
            finished(nil,error)
            
        }
        //3.发动网络请求
        if methodType == .GET {
            get(urlString, parameters: parameters, headers: nil, progress: nil, success: successCallBack, failure: failureCallBack)
        }else{
            post(urlString, parameters: parameters, headers: nil, progress: nil, success: successCallBack, failure: failureCallBack)
        }
        
        
    }
    
    func request666(methodType:RequestType,urlString:String,parameters : [String:Any]?,finished : @escaping(_ result :Any?, _ error : Error? )->()){
        //1.定义成功的回调闭包
        let successCallBack:((URLSessionDataTask, Any?) -> Void)? = {(task : URLSessionDataTask?,result :Any?) -> Void in
            finished(result, nil)
        }
        //2.定义失败的回调闭包
        let failureCallBack:((URLSessionDataTask?, Error) -> Void)? = { (task : URLSessionDataTask?,error : Error) -> Void in
            finished(nil,error)
            
        }
        //3.发动网络请求
        if methodType == .GET {
            get(urlString, parameters: parameters, headers: nil, progress: nil, success: successCallBack, failure: failureCallBack)
        }else{
            post(urlString, parameters: parameters, headers: nil, progress: nil, success: successCallBack, failure: failureCallBack)
        }
        
        
    }
    
}
//MARK:-请求AccessToken
extension NetworkTools{
    func loadAccessToken(code:String,finished:@escaping(_ result:[String : Any]?,_ error : Error?) -> ()){
        //1.获取请求的URLString
        let urlString = tockenURL
        
        //2.获取请求的参数
        let parameters = ["client_id" :client_id,
                          "client_secret" : client_secret,
                          "grant_type" : "authorization_code",
                          "redirect_uri" : redirect_uri,
                          "code" : code]
        //3.发送网络请求
        //        request(methodType: .POST, urlString: urlString, parameters: parameters) { (result, error) in
        //            //result as? [String : AnyObject]判断是否是字典
        //            finished(result as? [String : AnyObject], error as NSError?)
        //        }
        request(methodType: .POST, urlString: urlString, parameters: parameters  ) { result, error in
            //result as? [String : AnyObject]判断是否是字典
            finished(result as? [String : Any], error as Error?)
        }
    }
}

//MARK:-请求用户的信息
extension NetworkTools{
    func loadUserInfo(access_token : String, uid : String, finished : @escaping(_ result : [String :Any]?, _ error : Error?) ->()){
        //1.获取请求的URLString
        let urlSting = userURL
        
        //2.获取请求的参数
        let parameters = ["access_token" : access_token, "uid" : uid]
        //3.发送网络请求
        request(methodType: .GET, urlString: urlSting, parameters: parameters) { (result, error) in
            finished(result as? [String : Any],error as Error?)
        }
    }
}

//MARK:--请求首页数据
extension NetworkTools{
    func loadStatuses(since_id : Int,max_id : Int, finished : @escaping(_ result :[String : Any]?, _ error : Error?) ->()){
        //1.获取请求的URLString
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        //2.获取请求的参数
        let accessToken = (FYUserAccountViewModel().account?.access_token)!
        let parmeters = ["access_token":accessToken,"since_id" : "\(since_id)", "max_id" : "\(max_id)"]
        //3.发送网络请求
        request(methodType: .GET, urlString: urlString, parameters: parmeters) { (result, error) in
            //1.获取字典的数据
            guard let resultDict = result as? [String : Any] else{
                finished(nil, error)
                return
            }
            //2.将数组数据回调给外界控制器
            finished(resultDict[""] as? [String : Any], error)
        }
        
        
    }
}

// MARK:-发送微博
extension NetworkTools{
    func sendStatus(statusText : String, isSuccess :@escaping (_ isSuccess : Bool) ->()){
        //1.获取请求的URLString
        let  urlString = "https://api.weibo.com/2/statuses/update.json"
        
        //2.获取请求的参数
        let parmeters:[String : Any]? = ["access_token" : (FYUserAccountViewModel().account?.access_token) as Any, "status" : statusText]
        //3.发送网络请求
        self.request666(methodType: .POST, urlString: urlString, parameters: parmeters ) { (result, error) in
            if result != nil{
                isSuccess(true)
            }else{
                isSuccess(false)
            }
        }
    }
}

// MARK:-发送微博并且携带照片
extension NetworkTools{
    func sendStasus(statusText : String, image : UIImage, isSuccess : (_ isSuccess : Bool) ->()) {
        //1.获取请求的URLString
        let urlString = "https://api.weibo.com/2/statuses/upload.json"
        //2.获取请求的参数
        let  parameters = ["access_token" : (FYUserAccountViewModel().account?.access_token)!, "status" : statusText]
        //3.发送网络请求
        
        post(urlString, parameters: parameters, headers: nil) { formData in
            if let imageData = image.jpegData(compressionQuality: 0.5) {
                formData.appendPart(withFileData: imageData, name: "pic", fileName: "123.png", mimeType: "image/png")
                
            }
        } progress: { _ in
            
        } success: { _, _ in
            
        } failure: { _, error in
            print(error)
        }
        
        
    }
}
